// Copyright (c) Microsoft Corporation.
// Licensed under the MIT License.

/**
 * Demonstrates how to use either an Azure Active Directory (RBAC) or an
 * API Key to authenticate a FormRecognizerClient
 */

// To use an API Key, import `AzureKeyCredential` from the Form Recognizer package
const { FormRecognizerClient, AzureKeyCredential } = require("@azure/ai-form-recognizer");

// To use Azure AD, import `DefaultAzureCredential` from the `@azure/identity` package
const { DefaultAzureCredential } = require("@azure/identity");

const fs = require("fs");

// Load the .env file if it exists
require("dotenv").config();

// You will need to set this environment variables or edit the following values
const endpoint = process.env["FORM_RECOGNIZER_ENDPOINT"] || "<cognitive services endpoint>";

/**
 * Create a client using Azure Active Directory to authenticate
 */
async function useAad() {
  console.log("-- Azure Active Directory --");

  // DefaultAzureCredential expects the following three environment variables:
  // - AZURE_TENANT_ID: The tenant ID in Azure Active Directory
  // - AZURE_CLIENT_ID: The application (client) ID registered in the AAD tenant
  // - AZURE_CLIENT_SECRET: The client secret for the registered application
  const credential = new DefaultAzureCredential();

  const client = new FormRecognizerClient(endpoint, credential);

  await recognizeContentWithClient(client);
}

/**
 * Create a client using an API Key (Cognitive Services Subscription Key) to authenticate.
 */
async function useApiKey() {
  console.log("-- API Key --");

  // If using an API Key, you will need to set this environment variable
  const apiKey = process.env["FORM_RECOGNIZER_API_KEY"] || "<api key>";

  const credential = new AzureKeyCredential(apiKey);

  const client = new FormRecognizerClient(endpoint, credential);

  await recognizeContentWithClient(client);
}

/**
 * This function will use the client generated by `useApiKey` and `useAad`
 * for content recognition and print its output.
 */
async function recognizeContentWithClient(client) {
  const fileName = "assets/Invoice_6.pdf";

  if (!fs.existsSync(fileName)) {
    throw new Error(`Expecting file ${fileName} exists`);
  }

  const readStream = fs.createReadStream(fileName);

  const poller = await client.beginRecognizeContent(readStream);
  const pages = await poller.pollUntilDone();

  if (!pages || pages.length === 0) {
    throw new Error("Expecting non-empty list of pages!");
  }

  for (const page of pages) {
    console.log(
      `Page ${page.pageNumber}: width ${page.width} and height ${page.height} with unit ${page.unit}`
    );
    for (const table of page.tables) {
      for (const row of table.rows) {
        for (const cell of row.cells) {
          console.log(`cell [${cell.rowIndex},${cell.columnIndex}] has text ${cell.text}`);
        }
      }
    }
  }
}

async function main() {
  console.log("== Client Authentication Methods Sample ==");

  await useAad();

  await useApiKey();
}

main().catch((err) => {
  console.error("The sample encountered an error:", err);
});
